package paidaxing.blog.comment.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import paidaxing.blog.comment.dto.AuthorDTO;
import paidaxing.blog.comment.dto.CommentDTO;
import paidaxing.blog.comment.dto.request.CommentRequestDTO;
import paidaxing.blog.comment.dto.response.CommentResponseDTO;
import paidaxing.blog.comment.entity.Comments;
import paidaxing.blog.comment.mapper.CommentMapper;
import paidaxing.blog.comment.service.CommentService;
import paidaxing.blog.common.exception.BusinessException;
import paidaxing.blog.core.service.UserInfoService;
import paidaxing.blog.core.service.PostInfoService;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommentServiceImpl implements CommentService {
    @Resource
    private CommentMapper commentMapper;
    
    @Resource
    private UserInfoService userInfoService;
    
    @Resource
    private PostInfoService postInfoService;

    @Override
    public CommentDTO createComment(CommentRequestDTO commentRequestDTO) {
        // 验证参数
        if (commentRequestDTO.getPostId() == null) {
            throw new BusinessException("文章ID不能为空");
        }
        
        // 验证文章是否存在
        PostInfoService.PostInfoDTO post = postInfoService.getPostInfoById(commentRequestDTO.getPostId());
        if (post == null) {
            throw new BusinessException("评论的文章不存在或已被删除");
        }
        
        Comments comments = new Comments();
        BeanUtils.copyProperties(commentRequestDTO, comments);
        comments.setCreatedAt(new Date());
        comments.setUpdatedAt(new Date());
        comments.setDeleted(0);
        comments.setLikeCount(0);
        
        // 设置当前登录用户ID
        Long currentUserId = StpUtil.getLoginIdAsLong();
        comments.setUserId(currentUserId);
        
        // 设置IP地址和UserAgent（实际项目中应从请求上下文中获取）
        comments.setIpAddress("127.0.0.1");
        comments.setUserAgent("unknown");
        
        int result = commentMapper.insert(comments);
        if (result <= 0) {
            throw new BusinessException("评论创建失败");
        }
        
        CommentDTO commentDTO = new CommentDTO();
        BeanUtils.copyProperties(comments, commentDTO);
        return commentDTO;
    }

    @Override
    public CommentDTO getCommentById(Long id) {
        Comments comments = commentMapper.queryById(id);
        if (comments == null || comments.getDeleted() == 1) {
            return null;
        }
        
        CommentDTO commentDTO = new CommentDTO();
        BeanUtils.copyProperties(comments, commentDTO);
        return commentDTO;
    }

    @Override
    public CommentDTO updateComment(Long id, CommentRequestDTO commentRequestDTO) {
        Comments existingComment = commentMapper.queryById(id);
        if (existingComment == null || existingComment.getDeleted() == 1) {
            return null;
        }
        
        // 检查权限：只能更新自己的评论
        Long currentUserId = StpUtil.getLoginIdAsLong();
        if (!existingComment.getUserId().equals(currentUserId)) {
            throw new BusinessException("无权更新他人评论");
        }
        
        Comments comments = new Comments();
        BeanUtils.copyProperties(commentRequestDTO, comments);
        comments.setId(id);
        comments.setUpdatedAt(new Date());
        
        int result = commentMapper.update(comments);
        if (result <= 0) {
            throw new BusinessException("评论更新失败");
        }
        
        return getCommentById(id);
    }

    @Override
    public boolean deleteComment(Long id) {
        Comments existingComment = commentMapper.queryById(id);
        if (existingComment == null || existingComment.getDeleted() == 1) {
            return false;
        }
        
        // 检查权限：只能删除自己的评论
        Long currentUserId = StpUtil.getLoginIdAsLong();
        if (!existingComment.getUserId().equals(currentUserId)) {
            throw new BusinessException("无权删除他人评论");
        }
        
        int result = commentMapper.deleteById(id);
        return result > 0;
    }

    @Override
    public List<CommentResponseDTO> getCommentsTreeByPostId(Long postId) {
        // 验证参数
        if (postId == null) {
            throw new BusinessException("文章ID不能为空");
        }
        
        // 验证文章是否存在
        PostInfoService.PostInfoDTO post = postInfoService.getPostInfoById(postId);
        if (post == null) {
            throw new BusinessException("评论的文章不存在或已被删除");
        }
        
        // 获取该文章下的所有评论
        List<Comments> commentsList = commentMapper.selectCommentsByPostId(postId);
        
        // 转换为CommentResponseDTO列表
        List<CommentResponseDTO> commentDTOList = commentsList.stream().map(comment -> {
            CommentResponseDTO dto = new CommentResponseDTO();
            BeanUtils.copyProperties(comment, dto);
            
            // 创建并填充作者信息
            AuthorDTO author = new AuthorDTO();
            if (comment.getUserId() != null) {
                UserInfoService.UserInfoDTO user = userInfoService.getPublicUserInfoById(comment.getUserId());
                if (user != null) {
                    author.setId(user.getId());
                    author.setUsername(user.getUsername());
                    author.setNickname(user.getNickname());
                    author.setAvatar(user.getAvatar());
                } else {
                    author.setId(comment.getUserId());
                    author.setUsername("user_" + comment.getUserId());
                    author.setNickname("匿名用户");
                }
            } else {
                author.setNickname("匿名用户");
            }
            author.setAvatar(comment.getUserAvatar());
            dto.setAuthor(author);
            
            return dto;
        }).collect(Collectors.toList());
        
        // 构建评论树
        return buildCommentTree(commentDTOList);
    }

    @Override
    public List<CommentDTO> getCommentsByPostId(Long postId, Integer page, Integer size) {
        // 验证参数
        if (postId == null) {
            throw new BusinessException("文章ID不能为空");
        }
        
        // 验证文章是否存在
        PostInfoService.PostInfoDTO post = postInfoService.getPostInfoById(postId);
        if (post == null) {
            throw new BusinessException("评论的文章不存在或已被删除");
        }
        
        int offset = (page - 1) * size;
        List<Comments> commentsList = commentMapper.selectCommentsByPostIdAndPage(postId, offset, size);
        
        return commentsList.stream().map(comment -> {
            CommentDTO dto = new CommentDTO();
            BeanUtils.copyProperties(comment, dto);
            return dto;
        }).collect(Collectors.toList());
    }
    
    /**
     * 构建评论树结构
     * @param commentList 评论列表
     * @return 树形结构的评论列表
     */
    private List<CommentResponseDTO> buildCommentTree(List<CommentResponseDTO> commentList) {
        // 创建一个Map来存储所有评论，key为评论ID
        Map<Long, CommentResponseDTO> commentMap = new HashMap<>();
        for (CommentResponseDTO comment : commentList) {
            commentMap.put(comment.getId(), comment);
        }
        
        // 存储根评论（没有父评论的评论）
        List<CommentResponseDTO> rootComments = new ArrayList<>();
        
        for (CommentResponseDTO comment : commentList) {
            Long parentId = comment.getParentId();
            if (parentId == null || parentId == 0) {
                // 根评论
                comment.setChildren(new ArrayList<>());
                rootComments.add(comment);
            } else {
                // 子评论，找到父评论并添加到其children列表中
                CommentResponseDTO parentComment = commentMap.get(parentId);
                if (parentComment != null) {
                    if (parentComment.getChildren() == null) {
                        parentComment.setChildren(new ArrayList<>());
                    }
                    parentComment.getChildren().add(comment);
                }
            }
        }
        
        return rootComments;
    }
}